(function($){

    $.fn.rtTickets = function(options){

		var $editBtn, $pageCSS, $statusSor, $subjInput, Deep, areaOptions, ctrlFlag, hoverFlag, markCSS, rt_link, serialNum, statusOptions, unmarkCSS;

		$statusSor = $('<select style="display: none">\n\n</select>');

		statusOptions = $('<option value="open"> open </option>\n<option value="stall"> stalled </option>\n<option value="resolve"> resolved </option>\n<option value="kill" disabled=\'disabled\'> dead </option>');

		areaOptions = $('<option> None </option>\n<option>Declined</option>\n<option>Inquiries</option>\n<option>Interview Requested</option>\n<option>Placed - Admin</option>\n<option>Placed - CC</option>\n<option>Placed - PA</option>\n<option>Placed - US/UT</option>\n<option>Staff Requests</option>');

		$editBtn = $('<div id=\'edit\' style=\'position: absolute; display: table; text-align: right; color: RED; margin-top: -2px;\'>\n	<font style=\'font-size: 15px;\'>\n		[Edit]\n	</font>\n</div>');

		$subjInput = $('<p style="display: none" id="genTextWrap">\n	<input type="text" id="genTextArea"/>\n	<br />\n	<input type="submit" class="saveBtn" value="Save" />\n	<input type="submit" class="cancelBtn" value="Cancel">\n</p>');

		$pageCSS = '\
			<style type="text/css">\
			\
			.dropDownCell, .inputTypeCell{\
				height: 40px;\
			}\
			\
			.dropDownCell, #edit > font{\
				cursor: hand;\
			}\
			\
			#genTextArea{\
				width: 100%;\
				border: solid 1px gray;\
			}\
			\
			#msgDisplay{\
				height: 30px;\
				position: absolute;\
				text-align: center;\
			}\
			\
			#msgDisplay > font{\
				padding-left: 10px;\
				padding-right: 10px;\
				background-color: #A2CD5A !important;\
				font-size: 15px;\
				color: #000000;\
			}\
			\
			</style>';

		markCSS = {
    		'border-color': 'transparent',
    		'border-style': 'solid'
		};

		unmarkCSS = {
			'border-color': 'none',
			'border-style': 'none'
		};

		Deep = true;

		serialNum = /serial_num=(\d+)/;

		rt_link = "/rt/webrt.cgi";

		ctrlFlag = false;

		hoverFlag = false;

		var dbg;
		dbg = function(msg) {
			var target;
			target = $('#msgDisplay > font');
			$('#msgDisplay').css({
				'top': window.pageYOffset
			});
			$('#msgDisplay').css({
				'width': window.innerWidth
			});
			target.delay(100).hide(0).text(msg).fadeIn(200);
		};
    
        this.each(function(){

        	var $this, href, sn, _ref;
        	$this = $(this);
        	href = $('a', $this).attr('href');
        	if (sn = (_ref = href.match(serialNum)) != null ? _ref[1] : void 0) {
          		$this.addClass('ticket').attr({
            	'id': sn
          		});
          	$this.children('td:nth-child(3)').attr('id', 'status').addClass('dropDownCell');
          	$this.children('td:nth-child(8)').attr('id', 'area').addClass('dropDownCell');
          	$this.children('td:nth-child(5)').attr('id', 'subject').addClass('inputTypeCell');
          	$this.children('td:nth-child(9)').attr('id', 'requestor').addClass('inputTypeCell');
        }

        }).on('hover', 'td.inputTypeCell', function(){
          
        var cellPos;
        if (!$(this).children('#edit').length) hoverFlag = false;
        if (!hoverFlag & !ctrlFlag) {
          hoverFlag = true;
          cellPos = $(this).position();
          $(this).append($editBtn.clone());
          $(this).children('#edit').css({
            'width': $(this).innerWidth(),
            'top': cellPos.top,
            'left': cellPos.left
          });
          $(this).children('#edit').hide(0).delay(500).fadeIn(100);
        } else {

        }
        $(this).children('#edit').children('font').mousemove(function() {
          $(this).css({
            'text-decoration': 'underline'
          });
        });
        $(this).children('#edit').children('font').mouseleave(function() {
          $(this).css({
            'text-decoration': 'none'
          });
        });

        }).on('mouseleave', 'td.inputTypeCell', function() {
        if (hoverFlag) {
          $(this).children('#edit').remove();
          hoverFlag = false;
        } else {

        }
      });
      
      $('tbody').on('click', '#edit', function() {
        var $host, $textVal, ctrlWidth, currentValue, sn;
        hoverFlag = true;
        ctrlWidth = $(this).parent().width();
        $host = $(this).parent();
        sn = $host.parent().attr('id');
        if (!ctrlFlag) {
          currentValue = $host.children('font').text();
          $textVal = $host.children('font').clone(Deep);
          $host.empty().append($subjInput.clone());
          $host.css({
            'width': ctrlWidth
          });
          $host.children().fadeIn(300);
          $host.children('P').children('INPUT[id="genTextArea"]').val(currentValue).focus();
          ctrlFlag = true;
        } else {

        }
        $host.children('P').on('click', 'INPUT.saveBtn', function() {
          var newValue;
          newValue = $(this).prevAll('INPUT').val();
          if (newValue.toString() !== $textVal.text().toString()) {
            dbg('Waiting for server response..');
            $textVal.children('A').text("" + newValue + " [..]");
          }
          switch ($(this).parent().parent().attr('id')) {
            case 'subject':
              $.get(rt_link, {
                serial_num: sn,
                do_req_subject: true,
                subject: newValue
              }, function(data) {
                var exp, s;
                exp = /Request .* subject has been changed to ".*"./;
                $('#hiddenWrapper').html("<font> " + (s = data.match(exp)[0].toString()) + " </font>");
                dbg(s);
                $textVal.text(s.match(/"(.*?)"/)[1]);
                return false;
              });
              break;
            case 'requestor':
              $.get(rt_link, {
                serial_num: sn,
                do_req_user: true,
                recipient: newValue
              }, function(data) {
                $textVal.children('A').text(newValue);
                dbg('Requestor has been changed');
                return false;
              });
              break;
          }
          $(this).parent().replaceWith($textVal);
          ctrlFlag = false;
          return false;
        });
        $host.children('P').on('click', 'INPUT.cancelBtn', function() {
          $(this).parent().replaceWith($textVal);
          ctrlFlag = false;
          return false;
        });
      });

      $('tbody').on('click', '.dropDownCell', function() {
        var $statusVal, cellPos, columnType, ctrlHeight, ctrlWidth, currentValue, newOptions, sn;
        ctrlWidth = $(this).width();
        ctrlHeight = $(this).height();
        columnType = $(this).attr('id');
        sn = this.parentNode.id;
        if (!ctrlFlag) {
          ctrlFlag = true;
          switch ($(this).children('font').text()) {
            case 'resolved':
              currentValue = 'resolve';
              break;
            case 'stalled':
              currentValue = 'stall';
              break;
            default:
              currentValue = $(this).children('font').text();
          }
          switch (columnType) {
            case 'status':
              newOptions = statusOptions.clone();
              break;
            case 'area':
              newOptions = areaOptions.clone();
              if (currentValue.length !== 1) {
                currentValue = currentValue.substr(0, currentValue.length - 1);
              }
              break;
          }
          cellPos = $(this).position();
          $statusVal = $(this).children().clone(Deep);
          $(this).empty().append($statusSor.clone());
          $(this).children('SELECT').append(newOptions);
          $(this).children('SELECT').children("OPTION:contains(" + currentValue + ")").attr({
            "selected": "selected"
          });
          $(this).children('SELECT').show(100);
          $(this).children('SELECT').focus();
          $(this).change(function() {
            var selected, setAreaLink;
            dbg('Waiting for server response..');
            $statusVal.text("" + (selected = $(this).children()[0].value.toString()) + " [..]");
            switch (columnType) {
              case 'status':
                $.get(rt_link, {
                  serial_num: sn,
                  do_req_status: selected
                }, function(data) {
                  var exp, r, s;
                  exp = /Request #.* has been (opened|stalled|resolved)/;
                  $('#hiddenWrapper').html("<font> " + (s = data.match(exp)[0].toString()) + " </font>");
                  dbg(s);
                  r = s.match(/(opened|resolved|stalled)/gi)[0];
                  if (r === 'opened') r = 'open';
                  $statusVal.text(r);
                });
                break;
              case 'area':
                setAreaLink = "" + rt_link + "?serial_num=" + sn + "&area=" + selected + "&area=&do_req_area=true";
                $.get(setAreaLink, function(data) {
                  $statusVal.text("" + selected + " ");
                });
                break;
            }
            return this.childNodes[0].blur();
          });
          $(this).on('focusout', 'SELECT', function() {
            $(this).replaceWith($statusVal);
            ctrlFlag = false;
            return false;
          });
        } else {

        }
      });


    };
    
})(jQuery);

